#!/bin/sh

function parse_url()
{
	#Remove http:// prefix in url
	url=$(echo $url | sed 's/http:\/\///')

	#Split url into array with flag '/'	
	OLD_IFS="$IFS" 
	IFS="/"
	url_strarr=($url)
	IFS="$OLD_IFS" 

	#Fetch contents from url string array	
	len=${#url_strarr[@]}
	id=$len-4;
	if [ $len -lt 6 ]; then
		return 1
	fi
	filename=${url_strarr[$len-1]}
	project=${url_strarr[$id]%_*}
	version=${url_strarr[$id-1]}
	branch=${url_strarr[$id-2]}

	#Remove the filename postfix from url
	url=${url%/*}
	
	echo url=$url
	echo filename=$filename
	echo project=$project
	echo version=$version
	echo branch=$branch

	return 0	
}

##########################
#Please specify your login name and password here
username=
password=
##########################

url=$1
branch=
version=
project=
filename=

pushd $(dirname $0) >/dev/null

if parse_url; then
	#Create directory struct according to url
	if [ ! -d "$project" ]; then
		mkdir "$project"
	fi
	if [ ! -d "$project/$branch-$version" ]; then
		mkdir "$project/$branch-$version"
	fi

	#Download the ROM including the custom image	
	pushd "$project/$branch-$version" >/dev/null
	axel -n 10 --no-proxy http://"$username":"$password"@$url/$filename
	shift
	for custname in $@; do
		axel -n 10 --no-proxy http://"$username":"$password"@$url/$custname-$project.tar
	done
	popd >/dev/null
else
	#Just download the file indicated by url
	axel -n 10 --no-proxy http://"$username":"$password"@$url
fi

popd >/dev/null


